package org.jwap.server.utils;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URL;
import org.jwap.server.JWAP;

public class FileCore {
	public static String readTextFile(String path, boolean inRoot){
		byte[] fileData;

	    try {
	    	// Bundle bundle = Platform.getBundle(Activator.PLUGIN_ID);
	    	// URL fileURL = bundle.getEntry("templates/" + name + ".tpl");
	    	// URL fileURL = new URL("platform:/plugin/org.erialab.projects.plugin.eriadesigner/templates/" + name + ".tpl");
	    	String filePath;
	    	if ( inRoot ){
	    		filePath = JWAP.rootPath + path;
	    	} else {
	    		filePath = path;
	    	}
	    	
	    	File file = new File(filePath);
	    	URL fileURL = file.toURI().toURL();
	    	
	    	InputStream inputStream;
	    	try {
	    		inputStream = fileURL.openConnection().getInputStream(); 
	    	
	    		fileData = new byte[(int)file.length()];
		    	DataInputStream dis = new DataInputStream(inputStream);
		    	dis.readFully(fileData);
		    	dis.close();
		    	
	    	} catch (Exception e){
	    		inputStream = JWAP.class.getResourceAsStream('/' + path);
	    		
	    		if (inputStream != null) {
	    	        Writer writer = new StringWriter();

	    	        char[] buffer = new char[1024];
	    	        try {
	    	            Reader reader = new BufferedReader(
	    	                    new InputStreamReader(inputStream, "UTF-8"));
	    	            int n;
	    	            while ((n = reader.read(buffer)) != -1) {
	    	                writer.write(buffer, 0, n);
	    	            }
	    	        } finally {
	    	        	inputStream.close();
	    	        }
	    	        return writer.toString();
	    	    } else {        
	    	        return "";
	    	    }
	    	}
	    	
	    	
	    	/*
	    	BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

	        while(true) {
	            read = br.read(buffer, 0, N);
	            text += new String(buffer, 0, read);

	            if(read < N) {
	                break;
	            }
	        }
	        
	        br.close();
	        */
	    } catch(Exception ex) {
	        fileData = ex.toString().getBytes();
	    }

	    try {
			return new String(fileData, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}
	
	public static String readTextFile(String path){
		return readTextFile(path, true);
	}


}
